/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-05-07
 * Time: 23:04
 */

class Node {
    public int val;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _next) {
        val = _val;
        next = _next;
    }
}

public class Solution {
    public Node insert(Node head, int insertVal) {
        Node node = new Node(insertVal);
        // 插入的是第一个节点
        if (head == null){
            node.next = node;
            return node;
        }
        // 插入的是第二个节点
        if (head.next == head){
            head.next = node;
            node.next = head;
            return head;
        }
        Node cur = head;
        Node next = head.next;
        // 遍历一遍
        // 找到满足插入条件的位置
        // 如果遍历一遍都没有找到, 要么就是链表中的值全部相等
        // 要么就是本就该插到所给的 head 的前面
        while (next != head){
            // insertVal 值在 cur 和 next 之间
            if (cur.val <= insertVal && insertVal <= next.val) {
                break;
            }
            if (cur.val > next.val){
                // 要插入的值是最大值或者最小值
                if (cur.val <= insertVal || insertVal <= next.val){
                    break;
                }
            }
            cur = cur.next;
            next = next.next;
        }
        // 将节点插入
        node.next = next;
        cur.next = node;
        return head;
    }
}
